<template lang="pug">
.content
  .card
    .card-header(data-background-color='blue')
      h4.title {{title}}
      p.category 请填写以下用户信息
    .card-content
      form
        .row
          .col-md-6
            md-fg-input(label='MAC', :labelFloating='!userId', v-model='user.mac')
          .col-md-6
            md-fg-input(label='姓名', :labelFloating='!userId', v-model='user.name')
        .row
          .col-md-4
            md-fg-input(label='手机号', :labelFloating='!userId', v-model='user.phone')
          .col-md-4
            md-fg-input(type='email', label='电子邮件', :labelFloating='!userId', v-model='user.email')
          .col-md-4
            md-fg-input(label='公司', :labelFloating='!userId', v-model='user.company')
        .row
          .col-md-12
            md-fg-input(type='textarea', label='备注', :labelFloating='!userId', :rows='5', v-model='user.misc')
        md-button.btn.btn-primary.pull-right(@click.prevent='save') 保存
        .clearfix
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      user: {
        company: '',
        username: '',
        email: '',
        mac: '',
        misc: ''
      }
    }
  },
  computed: {
    userId() {
      return this.$route.params.id
    },
    userProfileUrl() {
      return '/users/id/' + this.userId
    },
    title() {
      return this.userId ? '编辑用户' : '新增用户'
    }
  },
  methods: {
    save() {
      if (this.userId) {
        axios.put(process.env.API_URL + '/users/id/' + this.userId, this.user)
        .then((response) => this.$router.push({path: this.userProfileUrl}))
        .catch((error) => console.log(error))
      } else {
        axios.post(process.env.API_URL + '/users', this.user)
        .then((response) => this.$router.go(-1))
        .catch((error) => console.log(error))
      }
    }
  },
  created() {
    if (this.userId) {
      axios.get(process.env.API_URL + '/users/id/' + this.userId)
      .then(res => {
        this.user = res.data
      })
      .catch((error) => console.log(error))
    }
  }
}
</script>

